<template>
    <!-- 主内容区域 -->
    <div :class="{ 'hidden-content': isFullscreen }">
        <el-container style="height: 100vh; border: 1px solid #eee;">
            <!-- 左侧菜单 -->
            <el-aside width="200px" style="background-color: #D3DCE6; overflow-y: auto;">
                <div style="padding: 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #999;">
                    <span style="font-weight: bold;">功能菜单</span>
                </div>
                <el-menu
                    default-active="shopList"
                    class="el-menu-vertical-demo"
                    @select="handleMenuSelect"
                    background-color="#D3DCE6"
                    text-color="#333"
                    active-text-color="#fff"
                >
                    <!-- 店铺管理菜单 -->
                    <el-sub-menu index="shopList">
                        <template #title>
                            <el-icon><Shop /></el-icon>
                            <span>店铺管理</span>
                        </template>
                        <el-menu-item
                            v-for="(shop, index) in shopData"
                            :key="shop.id"
                            :index="'shop_' + shop.id"
                            @click="handleShopSelect(shop.id)"
                        >
                            <template #title>
                                <el-image
                                    v-if="shop.logo"
                                    :src="'/img' + shop.logo"
                                    fit="cover"
                                    style="width: 24px; height: 24px; border-radius: 50%; margin-right: 8px; vertical-align: middle; cursor: pointer;"
                                    @click.stop="showFullscreenImage('/img' + shop.logo)"
                                ></el-image>
                                <span v-else style="display: inline-block; width: 24px; height: 24px; margin-right: 8px;"></span>

                                <span>{{ shop.shopName }}</span>
                                <span style="margin-left: 10px; font-size: 12px;">
                                    <el-tag :type="shop.status === 0 ? 'success' : 'danger'" size="mini">
                                        {{ shop.status === 0 ? '营业中' : '已关闭' }}
                                    </el-tag>
                                </span>
                            </template>
                        </el-menu-item>
                        <el-menu-item index="addShop" @click="showAddShopDialog">
                            <el-icon><Plus /></el-icon>
                            <span>新增店铺</span>
                        </el-menu-item>
                    </el-sub-menu>

                    <!-- 订单处理菜单 -->
                    <el-menu-item index="orderList">
                        <template #title>
                            <el-icon><Tickets /></el-icon>
                            <span>订单处理</span>
                        </template>
                    </el-menu-item>
                </el-menu>
            </el-aside>

            <!-- 右侧内容区域 -->
            <el-container>
                <el-main style="padding: 20px;">
                    <!-- 商品管理区域 (默认显示) -->
                    <div v-if="activeMenu === 'shopManagement'">
                        <!-- 当前店铺信息 -->
                        <div v-if="currentShop" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
                                <div style="display: flex; align-items: center;">
                                    <el-image
                                        v-if="currentShop.logo"
                                        :src="'/img' + currentShop.logo"
                                        fit="cover"
                                        style="width: 40px; height: 40px; border-radius: 50%; margin-right: 12px; cursor: pointer;"
                                        @click.stop="showFullscreenImage('/img' + currentShop.logo)"
                                    ></el-image>
                                    <h2 style="margin: 0;">{{ currentShop.shopName }}</h2>
                                </div>
                                <div>
                                    <el-button type="primary" size="mini" @click="showEditShopDialog(currentShop)" style="margin-right: 5px;">
                                        编辑
                                    </el-button>
                                    <el-button type="danger" size="mini" @click="handleDeleteShop(currentShop.id)">
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <div style="color: #666; margin-left: 52px;">
                                <p>店铺状态:
                                    <el-tag :type="currentShop.status === 0 ? 'success' : 'danger'">
                                        {{ currentShop.status === 0 ? '正在营业' : '关闭' }}
                                    </el-tag>
                                </p>
                                <p>开店时间: {{ currentShop.createTime }}</p>
                                <p>店铺描述: {{ currentShop.shopDesc || '无描述' }}</p>
                            </div>
                            <el-button type="info" @click="showDetailUser(currentShop)" style="margin-top: 10px; margin-left: 52px;">
                                查看店铺详情
                            </el-button>
                        </div>

                        <!-- 商品查询表单 -->
                        <el-form :model="productQuery" ref="productFormRef" label-width="auto" label-position="right" style="margin-bottom: 20px; background: #fff; padding: 15px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <el-form-item label="商品名称" prop="name">
                                        <el-input v-model="productQuery.name" placeholder="请输入商品名称" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="商品类型" prop="type">
                                        <el-input v-model="productQuery.type" placeholder="请输入商品类型" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="商品状态" prop="status">
                                        <el-select v-model="productQuery.status" placeholder="请选择状态" clearable>
                                            <el-option label="上架" value="0" />
                                            <el-option label="下架" value="1" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item>
                                        <el-button type="primary" @click="doProductList" style="margin-right: 10px;">查询</el-button>
                                        <el-button type="default" @click="resetProductQuery" style="margin-right: 10px;">重置</el-button>
                                        <el-button type="success" @click="showAddDialog">新增商品</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>

                        <!-- 商品表格 -->
                        <el-table
                            :data="currentProducts"
                            border
                            style="width: 100%; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                            empty-text="暂无商品数据"
                        >
                            <el-table-column prop="name" label="商品名称" width="200" />
                            <!-- 商品主图列 -->
                            <el-table-column label="商品主图" width="120">
                                <template #default="scope">
                                    <el-image
                                        v-if="scope.row.mainImg"
                                        :src="'/img' + scope.row.mainImg"
                                        fit="cover"
                                        style="width: 80px; height: 80px; border-radius: 4px; cursor: pointer;"
                                        @click.stop="showFullscreenImage('/img' + scope.row.mainImg)"
                                    ></el-image>
                                    <span v-else>无主图</span>
                                </template>
                            </el-table-column>
                            <!-- 商品图片列 -->
                            <el-table-column label="商品图片" width="120">
                                <template #default="scope">
                                    <div v-if="scope.row.img">
                                        <el-image
                                            :src="'/img' + scope.row.img.split(',')[0]"
                                            fit="cover"
                                            style="width: 80px; height: 80px; border-radius: 4px; cursor: pointer;"
                                            @click.stop="showFullscreenImage('/img' + scope.row.img.split(',')[0])"
                                        ></el-image>
                                        <span v-if="scope.row.img.split(',').length > 1" style="position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.5); color: white; border-radius: 50%; width: 18px; height: 18px; display: flex; align-items: center; justify-content: center; font-size: 12px;">
                                            {{ scope.row.img.split(',').length }}
                                        </span>
                                    </div>
                                    <span v-else>无图片</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="priceBefore" label="原价" width="100" />
                            <el-table-column prop="priceAfter" label="现价" width="100" />
                            <el-table-column prop="count" label="库存" width="80" />
                            <el-table-column prop="buyEd" label="已售" width="80" />
                            <el-table-column label="状态" width="100">
                                <template #default="scope">
                                    <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                                        {{ scope.row.status === '0' ? '上架' : '下架' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型" width="100" />
                            <el-table-column label="规格信息" min-width="300">
                                <template #default="scope">
                                    <div v-for="spec in scope.row.specs" :key="spec.id" style="margin-bottom: 5px;">
                                        <strong>{{ spec.specName }}:</strong>
                                        <span v-for="(value, index) in spec.values" :key="index">
                                            {{ value.value }}
                                            <template v-if="index !== spec.values.length - 1">、</template>
                                        </span>
                                    </div>
                                    <div v-if="!scope.row.specs || scope.row.specs.length === 0">
                                        无规格信息
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200">
                                <template #default="scope">
                                    <el-button
                                        type="primary"
                                        size="small"
                                        style="margin-right: 5px"
                                        @click="handleProductUpdate(scope.row)"
                                    >
                                        更新
                                    </el-button>
                                    <el-button
                                        type="danger"
                                        size="small"
                                        @click="handleProductOffline(scope.row)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页 -->
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pageNum"
                            :page-sizes="[5, 10, 20, 50]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="filteredProducts.length"
                            style="margin-top: 15px; text-align: right"
                        />
                    </div>

                    <!-- 订单处理区域 -->
                    <div v-if="activeMenu === 'orderManagement'">
                        <!-- 订单查询表单 -->
                        <el-form :model="orderQuery" ref="orderFormRef" label-width="auto" label-position="right" style="margin-bottom: 20px; background: #fff; padding: 15px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <el-form-item label="订单编号" prop="orderId">
                                        <el-input v-model="orderQuery.orderId" placeholder="请输入订单编号" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="商品名称" prop="productName">
                                        <el-input v-model="orderQuery.productName" placeholder="请输入商品名称" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="订单状态" prop="status">
                                        <el-select v-model="orderQuery.status" placeholder="请选择订单状态" clearable>
                                            <el-option label="全部" value="" />
                                            <el-option label="待付款" value="0" />
                                            <el-option label="已付款" value="1" />
                                            <el-option label="已发货" value="2" />
                                            <el-option label="已完成" value="3" />
                                            <el-option label="已取消" value="4" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item>
                                        <el-button type="primary" @click="doOrderList" style="margin-right: 10px;">查询</el-button>
                                        <el-button type="default" @click="resetOrderQuery" style="margin-right: 10px;">重置</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>

                        <!-- 订单表格 -->
                        <el-table
                            :data="currentOrders"
                            border
                            style="width: 100%; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                            empty-text="暂无订单数据"
                        >
                            <el-table-column prop="orderId" label="订单编号" width="180" />
                            <el-table-column prop="createTime" label="下单时间" width="180" />
                            <el-table-column prop="shopName" label="店铺名称" width="150" />
                            <el-table-column prop="productName" label="商品名称" width="180" />
                            <el-table-column prop="sku" label="规格" width="150" />
                            <el-table-column prop="count" label="数量" width="80" />
                            <el-table-column prop="totalAmount" label="实付金额" width="100" />
                            <el-table-column prop="buyerNickname" label="买家昵称" width="120" />
                            <el-table-column prop="buyerPhone" label="买家电话" width="120" />
                            <el-table-column prop="buyerAddress" label="买家地址" min-width="200" />
                            <el-table-column label="订单状态" width="120">
                                <template #default="scope">
                                    <el-tag :type="getStatusTagType(scope.row.status)">
                                        {{ getStatusText(scope.row.status) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200">
                                <template #default="scope">
                                    <el-button
                                        type="primary"
                                        size="small"
                                        style="margin-right: 5px"
                                        @click="handleUpdateOrderStatus(scope.row)"
                                    >
                                        更新状态
                                    </el-button>
                                    <el-button
                                        type="danger"
                                        size="small"
                                        @click="handleDeleteOrder(scope.row)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 订单分页 -->
                        <el-pagination
                            @size-change="handleOrderSizeChange"
                            @current-change="handleOrderCurrentChange"
                            :current-page="orderPageNum"
                            :page-sizes="[5, 10, 20, 50]"
                            :page-size="orderPageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="filteredOrders.length"
                            style="margin-top: 15px; text-align: right"
                        />
                    </div>
                </el-main>
            </el-container>
        </el-container>

        <!-- 详情 dialog -->
        <detail-shop ref="detailShopRef"></detail-shop>

        <!-- 新增商品对话框 -->
        <el-dialog title="新增商品" v-model="addDialogVisible" width="800px">
            <el-form :model="newProduct" ref="addProductFormRef" label-width="120px" label-position="top">
                <el-row :gutter="20">
                    <!-- 所属店铺 -->
                    <el-col :span="12">
                        <el-form-item label="所属店铺" prop="shopId" :rules="[{ required: true, message: '请选择所属店铺', trigger: 'change' }]">
                            <el-select v-model="newProduct.shopId" placeholder="请选择所属店铺">
                                <el-option
                                    v-for="shop in shopData"
                                    :key="shop.id"
                                    :label="`${shop.shopName}(${shop.status === 0 ? '营业中' : '已关闭'})`"
                                    :value="shop.id"
                                >
                                    <template #default>
                                        <el-image
                                            v-if="shop.logo"
                                            :src="'/img' + shop.logo"
                                            fit="cover"
                                            style="width: 18px; height: 18px; border-radius: 50%; margin-right: 6px; vertical-align: middle; cursor: pointer;"
                                            @click.stop="showFullscreenImage('/img' + shop.logo)"
                                        ></el-image>
                                        <span>{{ shop.shopName }}({{ shop.status === 0 ? '营业中' : '已关闭' }})</span>
                                    </template>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <!-- 商品名称 -->
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
                            <el-input v-model="newProduct.name" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品类型 -->
                    <el-col :span="12">
                        <el-form-item label="商品类型" prop="type" :rules="[{ required: true, message: '请输入商品类型', trigger: 'change' }]">
                            <el-input v-model="newProduct.type" placeholder="请输入商品类型"/>
                        </el-form-item>
                    </el-col>

                    <!-- 原价 -->
                    <el-col :span="12">
                        <el-form-item label="原价" prop="priceBefore" :rules="[{ required: true, type: 'number', message: '请输入原价', trigger: 'blur' }]">
                            <el-input v-model.number="newProduct.priceBefore" placeholder="请输入原价" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 现价 -->
                    <el-col :span="12">
                        <el-form-item label="现价" prop="priceAfter" :rules="[{ required: true, type: 'number', message: '请输入现价', trigger: 'blur' }]">
                            <el-input v-model.number="newProduct.priceAfter" placeholder="请输入现价" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 库存 -->
                    <el-col :span="12">
                        <el-form-item label="库存" prop="count" :rules="[{ required: true, type: 'number', message: '请输入库存数量', trigger: 'blur' }]">
                            <el-input v-model.number="newProduct.count" placeholder="请输入库存数量" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品主图 -->
                    <el-col :span="24">
                        <el-form-item label="商品主图" prop="mainImg">
                            <el-upload
                                drag
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleProductMainImageUploadSuccess"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将主图拖拽到此处，或 <em>点击上传</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M</div>
                                </template>
                            </el-upload>
                            <el-input v-model="newProduct.mainImg" placeholder="或输入商品主图URL" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品图片（支持多张） -->
                    <el-col :span="24">
                        <el-form-item label="商品图片" prop="img">
                            <el-upload
                                drag
                                multiple
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleProductImageUploadSuccess"
                                :on-error="handleProductImageUploadError"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将图片拖拽到此处，或 <em>点击上传（可多选）</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M，多张图片将自动用逗号分隔</div>
                                </template>
                            </el-upload>
                            <el-input v-model="newProduct.img" placeholder="或输入图片URL（多张用逗号分隔）" />
                        </el-form-item>
                    </el-col>

                    <!-- 规格信息编辑区域 -->
                    <el-col :span="24">
                        <el-form-item label="规格信息">
                            <el-table :data="newProduct.specs" border style="margin-bottom: 10px;">
                                <el-table-column label="规格名称" width="150">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.specName" placeholder="规格名称"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="规格值" width="470">
                                    <template #default="scope">
                                        <div
                                            v-for="(val, index) in scope.row.values"
                                            :key="index"
                                            style="display: inline-flex; align-items: center; margin-right: 8px;"
                                        >
                                            <el-input
                                                v-model="val.value"
                                                placeholder="值"
                                                style="width: 250px; margin-right: 4px;"
                                            ></el-input>
                                            <el-button
                                                type="text"
                                                icon="el-icon-delete"
                                                @click="removeAddSpecValue(scope.row, index)"
                                            >×</el-button>
                                        </div>
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            icon="el-icon-plus"
                                            @click="addAddSpecValue(scope.row)"
                                            class="c1"
                                        >添加值</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="150">
                                    <template #default="scope">
                                        <el-button
                                            type="danger"
                                            size="mini"
                                            icon="el-icon-delete"
                                            @click="removeAddSpec(scope.row)"
                                        >删除规格</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-button
                                type="success"
                                size="mini"
                                icon="el-icon-plus"
                                @click="addAddSpec"
                            >添加规格</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitProduct">确定</el-button>
            </template>
        </el-dialog>

        <!-- 编辑商品对话框 -->
        <el-dialog title="编辑商品" v-model="editDialogVisible" width="800px">
            <el-form :model="editProduct" ref="editProductFormRef" label-width="120px" label-position="top">
                <el-row :gutter="20">
                    <!-- 所属店铺 -->
                    <el-col :span="12">
                        <el-form-item label="所属店铺" prop="shopId" :rules="[{ required: true, message: '请选择所属店铺', trigger: 'change' }]">
                            <el-select v-model="editProduct.shopId" placeholder="请选择所属店铺">
                                <el-option
                                    v-for="shop in shopData"
                                    :key="shop.id"
                                    :label="`${shop.shopName}(${shop.status === 0 ? '营业中' : '已关闭'})`"
                                    :value="shop.id"
                                >
                                    <template #default>
                                        <el-image
                                            v-if="shop.logo"
                                            :src="'/img' + shop.logo"
                                            fit="cover"
                                            style="width: 18px; height: 18px; border-radius: 50%; margin-right: 6px; vertical-align: middle; cursor: pointer;"
                                            @click.stop="showFullscreenImage('/img' + shop.logo)"
                                        ></el-image>
                                        <span>{{ shop.shopName }}({{ shop.status === 0 ? '营业中' : '已关闭' }})</span>
                                    </template>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <!-- 商品名称 -->
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
                            <el-input v-model="editProduct.name" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品类型 -->
                    <el-col :span="12">
                        <el-form-item label="商品类型" prop="type" :rules="[{ required: true, message: '请输入商品类型', trigger: 'change' }]">
                            <el-input v-model="editProduct.type" placeholder="请输入商品类型"/>
                        </el-form-item>
                    </el-col>

                    <!-- 原价 -->
                    <el-col :span="12">
                        <el-form-item label="原价" prop="priceBefore" :rules="[{ required: true, type: 'number', message: '请输入原价', trigger: 'blur' }]">
                            <el-input v-model.number="editProduct.priceBefore" placeholder="请输入原价" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 现价 -->
                    <el-col :span="12">
                        <el-form-item label="现价" prop="priceAfter" :rules="[{ required: true, type: 'number', message: '请输入现价', trigger: 'blur' }]">
                            <el-input v-model.number="editProduct.priceAfter" placeholder="请输入现价" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 库存 -->
                    <el-col :span="12">
                        <el-form-item label="库存" prop="count" :rules="[{ required: true, type: 'number', message: '请输入库存数量', trigger: 'blur' }]">
                            <el-input v-model.number="editProduct.count" placeholder="请输入库存数量" type="number" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品主图 -->
                    <el-col :span="24">
                        <el-form-item label="商品主图" prop="mainImg">
                            <el-upload
                                drag
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleEditProductMainImageUploadSuccess"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将主图拖拽到此处，或 <em>点击上传</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M</div>
                                </template>
                            </el-upload>
                            <el-input v-model="editProduct.mainImg" placeholder="或输入商品主图URL" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品图片（支持多张） -->
                    <el-col :span="24">
                        <el-form-item label="商品图片" prop="img">
                            <el-upload
                                drag
                                multiple
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleEditProductImageUploadSuccess"
                                :on-error="handleEditProductImageUploadError"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将图片拖拽到此处，或 <em>点击上传（可多选）</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M，多张图片将自动用逗号分隔</div>
                                </template>
                            </el-upload>
                            <el-input v-model="editProduct.img" placeholder="或输入图片URL（多张用逗号分隔）" />
                        </el-form-item>
                    </el-col>

                    <!-- 商品状态 -->
                    <el-col :span="12">
                        <el-form-item label="商品状态" prop="status" :rules="[{ required: true, message: '请选择商品状态', trigger: 'change' }]">
                            <el-select v-model="editProduct.status" placeholder="请选择商品状态">
                                <el-option label="上架" value="0" />
                                <el-option label="下架" value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <!-- 规格信息 -->
                    <el-col :span="24">
                        <el-form-item label="规格信息">
                            <el-table :data="editProduct.specs" border style="margin-bottom: 10px;">
                                <el-table-column label="规格名称" width="150" aria-required="true">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.specName" placeholder="规格名称"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="规格值" width="470">
                                    <template #default="scope">
                                        <div
                                            v-for="(val, index) in scope.row.values"
                                            :key="index"
                                            style="display: inline-flex; align-items: center; margin-right: 8px;"
                                        >
                                            <el-input
                                                v-model="val.value"
                                                placeholder="值"
                                                style="width: 250px; margin-right: 4px;"
                                            ></el-input>
                                            <el-button
                                                type="text"
                                                icon="el-icon-delete"
                                                @click="removeSpecValue(scope.row, index)"
                                            >×</el-button>
                                        </div>
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            icon="el-icon-plus"
                                            @click="addSpecValue(scope.row)"
                                            class="c1"
                                        >添加值</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="150">
                                    <template #default="scope">
                                        <el-button
                                            type="danger"
                                            size="mini"
                                            icon="el-icon-delete"
                                            @click="removeSpec(scope.row)"
                                        >删除规格</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-button
                                type="success"
                                size="mini"
                                icon="el-icon-plus"
                                @click="addSpec"
                            >添加规格</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEditProduct">确定</el-button>
            </template>
        </el-dialog>

        <!-- 新增店铺对话框 -->
        <el-dialog title="新增店铺" v-model="addShopDialogVisible" width="600px">
            <el-form :model="newShop" ref="addShopFormRef" label-width="120px" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="店铺名称" prop="shopName" :rules="[{ required: true, message: '请输入店铺名称', trigger: 'blur' }]">
                            <el-input v-model="newShop.shopName" placeholder="请输入店铺名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺描述" prop="shopDesc">
                            <el-input v-model="newShop.shopDesc" placeholder="请输入店铺描述" type="textarea" rows="3" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺状态" prop="status" :rules="[{ required: true, message: '请选择店铺状态', trigger: 'change' }]">
                            <el-select v-model="newShop.status" placeholder="请选择店铺状态">
                                <el-option label="营业中" value="0" />
                                <el-option label="已关闭" value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺logo" prop="logo">
                            <el-upload
                                drag
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleShopLogoUploadSuccess"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将图片拖拽到此处，或 <em>点击上传</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M</div>
                                </template>
                            </el-upload>
                            <el-input v-model="newShop.logo" placeholder="或输入店铺logo URL" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="addShopDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddShop">确定</el-button>
            </template>
        </el-dialog>

        <!-- 编辑店铺对话框 -->
        <el-dialog title="编辑店铺" v-model="editShopDialogVisible" width="600px">
            <el-form :model="editShop" ref="editShopFormRef" label-width="120px" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="店铺名称" prop="shopName" :rules="[{ required: true, message: '请输入店铺名称', trigger: 'blur' }]">
                            <el-input v-model="editShop.shopName" placeholder="请输入店铺名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺描述" prop="shopDesc">
                            <el-input v-model="editShop.shopDesc" placeholder="请输入店铺描述" type="textarea" rows="3" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺状态" prop="status" :rules="[{ required: true, message: '请选择店铺状态', trigger: 'change' }]">
                            <el-select v-model="editShop.status" placeholder="请选择店铺状态">
                                <el-option label="营业中" value="0" />
                                <el-option label="已关闭" value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="店铺logo" prop="logo">
                            <el-upload
                                drag
                                style="width: 100%; margin-bottom: 10px;"
                                action="/api/shop/file/wanggou"
                                :on-success="handleEditShopLogoUploadSuccess"
                                :disabled="isUploading"
                            >
                                <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                                <div class="el-upload__text">将图片拖拽到此处，或 <em>点击上传</em></div>
                                <template #tip>
                                    <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M</div>
                                </template>
                            </el-upload>
                            <el-input v-model="editShop.logo" placeholder="或输入店铺logo URL" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="editShopDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEditShop">确定</el-button>
            </template>
        </el-dialog>

        <!-- 更新订单状态对话框 -->
        <el-dialog title="更新订单状态" v-model="updateOrderStatusVisible" width="500px">
            <el-form :model="currentOrder" ref="orderStatusFormRef" label-width="120px" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="订单编号" prop="orderId">
                            <el-input v-model="currentOrder.orderId" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="商品名称" prop="productName">
                            <el-input v-model="currentOrder.productName" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="买家信息" prop="buyerInfo">
                            <el-input :value="`${currentOrder.buyerNickname || ''}(${currentOrder.buyerPhone || ''})`" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="收货地址" prop="buyerAddress">
                            <el-input v-model="currentOrder.buyerAddress" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="当前状态" prop="status">
                            <el-input :value="getStatusText(currentOrder.status)" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="新状态" prop="newStatus" :rules="[{ required: true, message: '请选择新状态', trigger: 'change' }]">
                            <el-select v-model="currentOrder.newStatus" placeholder="请选择新状态">
                                <el-option label="待付款" value="0" />
                                <el-option label="已付款" value="1" />
                                <el-option label="已发货" value="2" />
                                <el-option label="已完成" value="3" />
                                <el-option label="已取消" value="4" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="updateOrderStatusVisible = false">取消</el-button>
                <el-button type="primary" @click="submitUpdateOrderStatus">确定</el-button>
            </template>
        </el-dialog>
    </div>

    <!-- 全屏图片查看器 -->
    <div
        v-if="isFullscreen"
        class="fullscreen-image-container"
        @click="closeFullscreen"
    >
        <div class="fullscreen-close-btn" @click="closeFullscreen">×</div>
        <img
            :src="fullscreenImage"
            class="fullscreen-image"
            alt="图片预览"
            @click.stop
        >
        <div class="fullscreen-hint">点击图片、空白区域或按ESC键关闭</div>
    </div>
</template>

<script setup>
import { onMounted, ref, computed, onBeforeUnmount } from 'vue'
import axios from "axios";
import DetailShop from "./DetailShop.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Shop, Tickets, UploadFilled } from '@element-plus/icons-vue';

// 全屏图片控制变量
const isFullscreen = ref(false);
const fullscreenImage = ref('');

// 控制当前显示的菜单内容
const activeMenu = ref('shopManagement'); // shopManagement 或 orderManagement

// 分页参数
const pageNum = ref(1);
const pageSize = ref(5);

// 订单分页参数
const orderPageNum = ref(1);
const orderPageSize = ref(5);

// 上传状态
const isUploading = ref(false);

// 店铺查询条件
const shop = ref({
    shopName: '',
    status: '', // 0表示正在营业，1表示关闭
    createTime: '',
    shopDesc: ''
});

// 店铺数据（新增logo字段）
const shopData = ref([]);

// 当前选中的店铺
const currentShopId = ref(null);
const currentShop = computed(() => {
    return shopData.value.find(shop => shop.id === currentShopId.value) || null;
});

// 商品查询条件
const productQuery = ref({
    name: '',
    type: '',
    status: ''
});

// 过滤后的商品列表（基于当前店铺和查询条件）
const filteredProducts = computed(() => {
    if (!currentShop.value || !currentShop.value.products) return [];

    return currentShop.value.products.filter(product => {
        if (productQuery.value.name && !product.name.includes(productQuery.value.name)) return false;
        if (productQuery.value.type && !product.type.includes(productQuery.value.type)) return false;
        if (productQuery.value.status !== '' && String(product.status) !== productQuery.value.status) return false;
        return true;
    });
});

// 分页后的商品列表
const currentProducts = computed(() => {
    const startIndex = (pageNum.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return filteredProducts.value.slice(startIndex, endIndex);
});

// 订单相关
const orderList = ref([]); // 所有订单
const orderQuery = ref({
    orderId: '',
    productName: '',
    status: ''
});

// 过滤后的订单列表
const filteredOrders = computed(() => {
    return orderList.value.filter(order => {
        if (orderQuery.value.orderId && !order.orderId.toString().includes(orderQuery.value.orderId.toString())) return false;
        if (orderQuery.value.productName && !order.productName.includes(orderQuery.value.productName)) return false;
        if (orderQuery.value.status !== '' && order.status !== parseInt(orderQuery.value.status)) return false;
        return true;
    });
});

// 分页后的订单列表
const currentOrders = computed(() => {
    const startIndex = (orderPageNum.value - 1) * orderPageSize.value;
    const endIndex = startIndex + orderPageSize.value;
    return filteredOrders.value.slice(startIndex, endIndex);
});

// 当前操作的订单
const currentOrder = ref({
    orderId: '',
    status: 0,
    newStatus: 0,
    productName: '',
    sellerId: '',
    buyerNickname: '',
    buyerPhone: '',
    buyerAddress: ''
});

// 订单状态更新对话框
const updateOrderStatusVisible = ref(false);

// 新增商品相关
const addDialogVisible = ref(false);
const addProductFormRef = ref();
const newProduct = ref({
    shopId: null,
    name: '',
    type: '',
    priceBefore: 0,
    priceAfter: 0,
    count: 0,
    buyEd: 0,
    mainImg: '', // 商品主图
    img: '',      // 商品图片（多张用逗号分隔）
    specs: []
});

// 编辑商品相关
const editDialogVisible = ref(false);
const editProductFormRef = ref();
const editProduct = ref({
    id: '',
    shopId: null,
    name: '',
    type: '',
    priceBefore: 0,
    priceAfter: 0,
    count: 0,
    buyEd: 0,
    status: "0",
    mainImg: '', // 商品主图
    img: '',      // 商品图片（多张用逗号分隔）
    specs: []
});

// 新增店铺相关
const addShopDialogVisible = ref(false);
const addShopFormRef = ref();

// 认证服务
import { AuthService } from '@/service/auth.ts'
const authService = new AuthService();
const userId = authService.getUserId();
console.log('User ID:', userId);

const newShop = ref({
    userId: userId,
    shopName: '',
    shopDesc: '',
    status: 0, // 默认营业中
    logo: ''
});

// 编辑店铺相关
const editShopDialogVisible = ref(false);
const editShopFormRef = ref();
const editShop = ref({
    id: 0,
    userId: userId,
    shopName: '',
    shopDesc: '',
    status: 0,
    logo: ''
});

// 详情组件相关
const detailShopRef = ref();

// 显示全屏图片
const showFullscreenImage = (imgUrl) => {
    fullscreenImage.value = imgUrl;
    isFullscreen.value = true;
    document.body.style.overflow = 'hidden'; // 禁止背景滚动
};

// 关闭全屏图片
const closeFullscreen = () => {
    isFullscreen.value = false;
    document.body.style.overflow = ''; // 恢复滚动
};

// ESC键关闭全屏图片的处理函数
const handleKeyDown = (e) => {
    if (e.key === 'Escape' && isFullscreen.value) {
        closeFullscreen();
    }
};

// 监听键盘事件
onMounted(() => {
    document.addEventListener('keydown', handleKeyDown);
    doList();
});

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
    document.removeEventListener('keydown', handleKeyDown);
});

// 菜单选择事件
const handleMenuSelect = (index) => {
    if (index === 'orderList') {
        activeMenu.value = 'orderManagement';
        getOrderList();
    } else if (index === 'addShop') {
        showAddShopDialog();
    } else if (index.startsWith('shop_')) {
        const shopId = parseInt(index.split('_')[1]);
        handleShopSelect(shopId);
        activeMenu.value = 'shopManagement';
    }
};

// 获取店铺列表
const doList = async () => {
    try {
        const { data } = await axios.get('/api/shop/with-products', {
            params: {
                userId: userId,
                shopName: shop.value.shopName,
                status: shop.value.status,
                createTime: shop.value.createTime,
                shopDesc: shop.value.shopDesc,
                pageNum: 1,
                pageSize: 100
            }
        });
        shopData.value = data.records || data;
        if (shopData.value.length > 0 && !currentShopId.value) {
            currentShopId.value = shopData.value[0].id;
        }
    } catch (error) {
        console.error("请求失败！原因：", error);
    }
};

// 获取订单列表
const getOrderList = async () => {
    try {
        const { data } = await axios.get('/api/shop/selectBySellerId', {
            params: {
                sellerId: userId
            }
        });
        orderList.value = data || [];
    } catch (error) {
        console.error("获取订单失败！原因：", error);
        ElMessage.error("获取订单失败，请稍后重试");
    }
};

// 切换店铺
const handleShopSelect = (shopId) => {
    currentShopId.value = Number(shopId);
    pageNum.value = 1;
};

// 商品查询
const doProductList = () => {
    pageNum.value = 1;
};

// 订单查询
const doOrderList = () => {
    orderPageNum.value = 1;
};

// 重置商品查询条件
const resetProductQuery = () => {
    productQuery.value = { name: '', type: '', status: '' };
    pageNum.value = 1;
};

// 重置订单查询条件
const resetOrderQuery = () => {
    orderQuery.value = { orderId: '', productName: '', status: '' };
    orderPageNum.value = 1;
};

// 分页事件
const handleSizeChange = (val) => {
    pageSize.value = val;
    pageNum.value = 1;
};
const handleCurrentChange = (val) => {
    pageNum.value = val;
};

// 订单分页事件
const handleOrderSizeChange = (val) => {
    orderPageSize.value = val;
    orderPageNum.value = 1;
};
const handleOrderCurrentChange = (val) => {
    orderPageNum.value = val;
};

// 显示新增商品对话框
const showAddDialog = () => {
    if (!currentShopId.value) {
        ElMessage.warning("请先选择一个店铺");
        return;
    }

    const selectedShop = shopData.value.find(shop => shop.id === currentShopId.value);
    if (selectedShop && selectedShop.status !== 0) {
        ElMessage.warning("只有正在营业的店铺才能新增商品");
        return;
    }

    newProduct.value = {
        shopId: currentShopId.value,
        name: '',
        type: '',
        priceBefore: 0,
        priceAfter: 0,
        count: 0,
        buyEd: 0,
        mainImg: '',
        img: '',      // 初始化空字符串
        specs: []
    };
    addDialogVisible.value = true;
};

// 新增商品 - 规格操作
const addAddSpec = () => {
    newProduct.value.specs.push({ specName: "", values: [] });
};
const removeAddSpec = (row) => {
    const index = newProduct.value.specs.findIndex(item => item === row);
    if (index !== -1) newProduct.value.specs.splice(index, 1);
};
const addAddSpecValue = (row) => {
    if (!row.values) row.values = [];
    row.values.push({ value: "" });
};
const removeAddSpecValue = (row, index) => {
    if (row.values && index < row.values.length) row.values.splice(index, 1);
};

// 编辑商品 - 规格操作
const addSpec = () => {
    if (!editProduct.value.specs) editProduct.value.specs = [];
    editProduct.value.specs.push({ specName: "", values: [] });
};
const removeSpec = (row) => {
    const index = editProduct.value.specs.findIndex(item => item === row);
    if (index !== -1) editProduct.value.specs.splice(index, 1);
};
const addSpecValue = (row) => {
    if (!row.values) row.values = [];
    row.values.push({ value: "" });
};
const removeSpecValue = (row, index) => {
    if (row.values && index < row.values.length) row.values.splice(index, 1);
};

// 图片上传处理函数
const handleProductMainImageUploadSuccess = (response) => {
    newProduct.value.mainImg = response;
    ElMessage.success('主图上传成功');
};

// 新增商品图片上传成功回调
const handleProductImageUploadSuccess = (response) => {
    if (response && typeof response === 'string') {
        newProduct.value.img = newProduct.value.img
            ? `${newProduct.value.img},${response}`
            : response;
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error('图片路径格式错误');
    }
};

// 新增商品图片上传错误处理
const handleProductImageUploadError = () => {
    ElMessage.error('图片上传失败，请重试');
};

// 编辑商品主图上传
const handleEditProductMainImageUploadSuccess = (response) => {
    editProduct.value.mainImg = response;
    ElMessage.success('主图上传成功');
};

// 编辑商品图片上传成功回调
const handleEditProductImageUploadSuccess = (response) => {
    if (response && typeof response === 'string') {
        if (editProduct.value.img) {
            editProduct.value.img = `${editProduct.value.img},${response}`;
        } else {
            editProduct.value.img = response;
        }
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error('图片路径格式错误');
    }
};

// 编辑商品图片上传错误处理
const handleEditProductImageUploadError = () => {
    ElMessage.error('图片上传失败，请重试');
};

// 店铺logo上传
const handleShopLogoUploadSuccess = (response) => {
    newShop.value.logo = response;
    ElMessage.success('Logo上传成功');
};

// 编辑店铺logo上传
const handleEditShopLogoUploadSuccess = (response) => {
    editShop.value.logo = response;
    ElMessage.success('Logo上传成功');
};

// 提交新增商品
const submitProduct = async () => {
    if (!addProductFormRef.value) return;
    try {
        await addProductFormRef.value.validate();

        const selectedShop = shopData.value.find(shop => shop.id === newProduct.value.shopId);
        if (selectedShop && selectedShop.status !== 0) {
            ElMessage.warning("只有正在营业的店铺才能新增商品");
            return;
        }

        if (!Array.isArray(newProduct.value.specs)) newProduct.value.specs = [];
        const { data } = await axios.post('/api/shop/product/upload', newProduct.value);
        if (data.code === 200) {
            ElMessage.success('商品上架成功');
            addDialogVisible.value = false;
            doList();
        } else {
            ElMessage.error(data.message || '商品上架失败');
        }
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('商品上架失败：', error);
            ElMessage.error('商品上架失败，请稍后重试');
        }
    }
};

// 处理商品更新
const handleProductUpdate = (product) => {
    const selectedShop = shopData.value.find(shop => shop.id === product.shopId);
    if (selectedShop && selectedShop.status !== 0) {
        ElMessage.warning("只有正在营业的店铺商品才能编辑");
        return;
    }

    editProduct.value = JSON.parse(JSON.stringify(product));
    editDialogVisible.value = true;
};

// 提交编辑商品
const submitEditProduct = async () => {
    if (!editProductFormRef.value) return;
    try {
        await editProductFormRef.value.validate();

        const selectedShop = shopData.value.find(shop => shop.id === editProduct.value.shopId);
        if (selectedShop && selectedShop.status !== 0) {
            ElMessage.warning("只有正在营业的店铺商品才能编辑");
            return;
        }

        if (!Array.isArray(editProduct.value.specs)) editProduct.value.specs = [];
        const { data } = await axios.put('/api/shop/product/update', editProduct.value);
        if (data.code === 200) {
            ElMessage.success('商品更新成功');
            editDialogVisible.value = false;
            doList();
        } else {
            ElMessage.error(data.message || '商品更新失败');
        }
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('商品更新失败：', error);
            ElMessage.error('商品更新失败，请稍后重试');
        }
    }
};

// 处理商品下架
const handleProductOffline = async (product) => {
    const selectedShop = shopData.value.find(shop => shop.id === product.shopId);
    if (selectedShop && selectedShop.status !== 0) {
        ElMessage.warning("只有正在营业的店铺商品才能删除");
        return;
    }

    try {
        const confirmResult = await ElMessageBox.confirm(
            '确定要删除该商品吗？',
            '删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );
        if (confirmResult === 'confirm') {
            const { data } = await axios.delete('/api/product', { data: { id: product.id } });
            if (data === 1) {
                ElMessage.success('商品删除成功');
                doList();
            } else {
                ElMessage.error('商品删除失败');
            }
        }
    } catch (error) {
        if (error.message !== 'cancel') {
            console.error('删除失败：', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    }
};

// 查看店铺详情
const showDetailUser = (obj) => {
    detailShopRef.value.handleDetailData(obj);
};

// 显示新增店铺对话框
const showAddShopDialog = () => {
    newShop.value = {
        userId: userId,
        shopName: '',
        shopDesc: '',
        status: 0,
        logo: ''
    };
    addShopDialogVisible.value = true;
};

// 显示编辑店铺对话框
const showEditShopDialog = (shop) => {
    editShop.value = JSON.parse(JSON.stringify(shop));
    editShopDialogVisible.value = true;
};

// 提交新增店铺
const submitAddShop = async () => {
    if (!addShopFormRef.value) return;
    try {
        await addShopFormRef.value.validate();

        const { data } = await axios.post('/api/shop/shopMS', newShop.value);
        if (data.code === 200) {
            ElMessage.success('店铺创建成功');
            addShopDialogVisible.value = false;
            doList();
        } else {
            ElMessage.error(data.message || '店铺创建失败');
        }
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('店铺创建失败：', error);
            ElMessage.error('店铺创建失败，请稍后重试');
        }
    }
};

// 提交编辑店铺
const submitEditShop = async () => {
    if (!editShopFormRef.value) return;
    try {
        await editShopFormRef.value.validate();

        const { data } = await axios.put('/api/shop/shopMS', editShop.value);
        if (data.code === 200) {
            ElMessage.success('店铺更新成功');
            editShopDialogVisible.value = false;
            doList();
        } else {
            ElMessage.error(data.message || '店铺更新失败');
        }
    } catch (error) {
        if (error.name !== 'ValidationError') {
            console.error('店铺更新失败：', error);
            ElMessage.error('店铺更新失败，请稍后重试');
        }
    }
};

// 处理店铺删除
const handleDeleteShop = async (shopId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确定要删除该店铺吗？删除后店铺内所有商品也将被删除',
            '删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );
        if (confirmResult === 'confirm') {
            const { data } = await axios.delete(`/api/shop/shopMS/${shopId}`);
            if (data.code === 200) {
                ElMessage.success('店铺删除成功');
                if (currentShopId.value === shopId) {
                    currentShopId.value = shopData.value.length > 0 ? shopData.value[0].id : null;
                }
                doList();
            } else {
                ElMessage.error(data.message || '店铺删除失败');
            }
        }
    } catch (error) {
        if (error.message !== 'cancel') {
            console.error('店铺删除失败：', error);
            ElMessage.error('店铺删除失败，请稍后重试');
        }
    }
};

// 订单状态文本转换
const getStatusText = (status) => {
    switch (status) {
        case 0: return '待付款';
        case 1: return '已付款';
        case 2: return '已发货';
        case 3: return '已完成';
        case 4: return '已取消';
        default: return '未知状态';
    }
};

// 订单状态标签样式
const getStatusTagType = (status) => {
    switch (status) {
        case 0: return 'info';
        case 1: return 'primary';
        case 2: return 'success';
        case 3: return 'success';
        case 4: return 'danger';
        default: return 'warning';
    }
};

// 处理订单状态更新
const handleUpdateOrderStatus = (order) => {
    currentOrder.value = {
        ...order,
        newStatus: order.status
    };
    updateOrderStatusVisible.value = true;
};

// 提交订单状态更新
const submitUpdateOrderStatus = async () => {
    if (!currentOrder.value.orderId) {
        ElMessage.warning("订单ID无效");
        return;
    }

    const requestData = {
        orderId: currentOrder.value.orderId,
        newStatus: Number(currentOrder.value.newStatus),
        sellerId: Number(userId)
    };

    try {
        const { data } = await axios.put(
            '/api/shop/updateOrderStatus',
            null,
            { params: requestData }
        );

        if (data > 0) {
            ElMessage.success('订单状态更新成功');
            updateOrderStatusVisible.value = false;
            getOrderList();
        } else {
            ElMessage.error('更新失败：无权限或订单不存在');
        }
    } catch (error) {
        console.error('更新订单状态失败：', error);
        ElMessage.error('网络请求失败，请稍后重试');
    }
};

// 处理订单删除
const handleDeleteOrder = async (order) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            `确定要删除订单 ${order.orderId} 吗？`,
            '删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );

        if (confirmResult === 'confirm') {
            const { data } = await axios.delete('/api/shop/deleteOrder', {
                params: {
                    orderId: order.orderId,
                    sellerId: userId
                }
            });

            if (data > 0) {
                ElMessage.success('订单删除成功');
                getOrderList();
            } else {
                ElMessage.error('订单删除失败，请检查权限');
            }
        }
    } catch (error) {
        if (error.message !== 'cancel') {
            console.error('删除订单失败：', error);
            ElMessage.error('删除订单失败，请稍后重试');
        }
    }
};

// 页面加载时获取数据
onMounted(() => {
    doList();
});
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
}
.el-main {
    background-color: #F5F7FA;
}
.c1 {
    width: 250px;
}
.el-image__error {
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
}
/* 图片数量指示器样式 */
.el-table .cell {
    position: relative;
}
/* 提高图片预览的层级，确保覆盖表单 */
::v-deep .el-image-viewer__wrapper {
    z-index: 3000 !important; /* 设置足够高的层级（超过页面其他元素） */
}

/* 全屏图片样式 */
.fullscreen-image-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    cursor: zoom-out;
}

.fullscreen-image {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
    cursor: default;
}

.fullscreen-close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    color: white;
    font-size: 30px;
    background: rgba(0, 0, 0, 0.5);
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.fullscreen-close-btn:hover {
    background: rgba(255, 0, 0, 0.7);
}

.fullscreen-hint {
    position: absolute;
    bottom: 20px;
    color: white;
    font-size: 14px;
    background: rgba(0, 0, 0, 0.5);
    padding: 5px 10px;
    border-radius: 4px;
}

/* 当全屏时隐藏主内容 */
.hidden-content {
    visibility: hidden;
    position: fixed;
    width: 100%;
    height: 100%;
}
</style>
